<?php
namespace app\api\controller\foodcash;

use app\api\controller\foodcash\Controller;
use app\api\model\foodcash\Goods as GoodsModel;
use app\api\model\Category as CategoryModel;

/**
 * 商品控制器
 */
class Goods extends Controller
{
    /**
     * 商品列表
     */
    public function food()
    {
        $model = new GoodsModel;
        $category = array_values(CategoryModel::getCacheTree($this->shop_id));
        $result = $model->foodGoodsList($this->shop_id,$category,$this->user['user_id']);
        $category = $result['category'];
        $order_total_num = $result['cartlist']['order_total_num'];
        $order_total_price = $result['cartlist']['order_total_price'];
        $goodslist = $result['cartlist']['goods_list'];
        return $this->renderSuccess(compact('category','order_total_num','order_total_price','goodslist'));
    }
    
    
    
    
    
    
    

    /**
     * 商品列表
     */
    public function lists()
    {
        $model = new GoodsModel;
		$category = array_values(CategoryModel::getCacheTree($this->shop_id));
		$category = $model->getGoodsList($this->shop_id,$category);
		return $this->renderSuccess(compact('category'));
    }
    
    /**
     * 添加
     */
    public function add()
    {
        $model = new GoodsModel;
        if($model->add($this->request->post('goods'),$this->shop_id)){
            return $this->renderMsg('添加成功');
        }
        $error = $model->getError() ?: '添加失败';
        return $this->renderError($error);
    }

    /**
     * 编辑
     */
    public function edit($id)
    {
        //详情
        $model = GoodsModel::detail($id);
        if (!$this->request->isPost()) {
            //分类
            $category = CategoryModel::getCacheAll($this->shop_id);
            // 多规格信息
            $specData = 'null';
            if($model['spec_type'] == 20){
                $specData = get_many_spec_data($model['spec_rel'], $model['spec']);  
            }
            return $this->renderSuccess(compact('model', 'category', 'specData'));
        }
        // 更新记录
        if ($model->edit($this->request->post('goods'))) {
             return $this->renderMsg('更新成功');
        }
        $error = $model->getError() ?: '更新失败';
        return $this->renderError($error);
    }

    /**
     * 删除商品
     */
    public function delete($id)
    {
        $model = new GoodsModel;
        if($model->remove($id)){
            return $this->renderMsg('删除成功');
        }
        $error = $model->getError() ?: '删除失败';
        return $this->renderError($error);
    }

    /**
     * 上架/下架
     */
    public function status($id)
    {
        $model = GoodsModel::get($id);
        if($model->status()){
            return $this->renderMsg('操作成功');
        }
        $error = $model->getError() ?: '操作失败';
        return $this->renderError($error);
    }
	
}
